package life.system.order.service.impl;

import life.system.common.enume.OrderStatusEnum;
import life.system.common.utils.DesUtil;
import life.system.order.entity.OrderEntity;
import life.system.order.feign.ThirdPartyFeignService;
import life.system.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import life.system.common.utils.PageUtils;
import life.system.common.utils.Query;

import life.system.order.dao.PaymentInfoDao;
import life.system.order.entity.PaymentInfoEntity;
import life.system.order.service.PaymentInfoService;
import org.springframework.transaction.annotation.Transactional;


@Service("paymentInfoService")
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoDao, PaymentInfoEntity> implements PaymentInfoService {

    @Autowired
    OrderService orderService;
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PaymentInfoEntity> page = this.page(
                new Query<PaymentInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Transactional
    public String saveByOrderSn( String orderSn) throws Exception {
        // 1、订单号加密
        DesUtil des = new DesUtil("zxslzyx");
        String encryptOrderSn = des.encrypt(orderSn);

        // 2、将加密后的订单号生成二维码并存储到oss上保留存储地址
        String qrCodeUrl = thirdPartyFeignService.PrintQRCode(encryptOrderSn);

        // 3、根据订单号获取订单信息
        OrderEntity order = orderService.getOrderByOrderSn(orderSn);

        // 4、修改订单状态
        order.setStatus(OrderStatusEnum.PAYED.getCode());
        order.setModifyTime(new Date());
        order.setAutoConfirmDay(7);
        order.setQcCode(qrCodeUrl);
        order.setPaymentTime(new Date());
        orderService.updateById(order);

        // 5、保存支付信息
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setOrderId(order.getId());
        infoEntity.setOrderSn(order.getOrderSn());
        infoEntity.setTotalAmount(order.getPayAmount());
        infoEntity.setPaymentStatus(String.valueOf(OrderStatusEnum.PAYED.getCode()));
        infoEntity.setCreateTime(order.getCreateTime());
        infoEntity.setConfirmTime(new Date());
        this.save(infoEntity);

        return qrCodeUrl;
    }
}